package com.ysqcould.mp.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ysqcould.allocation.mapper.WxUserMapper;
import com.ysqcould.common.enums.WxResultStatus;
import com.ysqcould.common.exception.WxApiException;
import com.ysqcould.common.utils.spring.SpringUtils;
import com.ysqcould.mp.domain.MpToken;
import com.ysqcould.mp.domain.vo.WxResultBody;
import com.ysqcould.mp.mapper.MpTokenMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ysqcould.common.enums.MpBaseResp.FREQ_CONTROL;
import static com.ysqcould.common.enums.MpBaseResp.INVALID_SESSION;

/**
 * 文章采集工具类
 * @author jcd
 */
public class CollectUtils {
    private static final Map<String,String> URL_MAP=new HashMap<>();

    static{
        // 公众号标题搜索接口
        URL_MAP.put("searchbiz", "https://mp.weixin.qq.com/cgi-bin/searchbiz");
        /**公众号文章搜索接口*/
        URL_MAP.put("findListEx","https://mp.weixin.qq.com/cgi-bin/appmsg");
    }

    /**
     * 搜素公众号唯一id
     * @param keyword 公众号
     * @param count 条数
     * @return wxResultBody 微信返回结果
     */
    public static WxResultBody searchBiz(String keyword,String count){
        Map<String, String> params = new HashMap<>(10);
        params.put("action", "search_biz");
        params.put("begin", "0");
        params.put("count", count);
        params.put("query", keyword);
        params.put("token", getMpToken());
        params.put("lang", "zh_CN");
        params.put("f", "json");
        params.put("ajax", "1");

        WxResultBody<List<Map>> wxResultBody = parseWxResultBody(HttpUtils.doGet(URL_MAP.get("searchbiz"), params),
                new TypeReference<WxResultBody<List<Map>>>() {}
        );
        System.out.println(wxResultBody);

        return wxResultBody;
    }



    /**
     *搜索公众号历史文章
     * @param pageNo 翻页数据
     * @param fakeId 公众号唯一id
     * @return wxResultBody 微信返回结果
     */
    public static WxResultBody findListEx(String pageNo,String fakeId){
        Map<String, String> params = new HashMap<>(10);
        params.put("action", "list_ex");
        params.put("begin", ((Integer.parseInt(pageNo) - 1) * 5) + "");
        params.put("count", "5"); // 条数固定，5条，调大也没用
        params.put("fakeid", fakeId);
        params.put("token", getMpToken());
        params.put("type", "9");
        params.put("query", "");
        params.put("lang", "zh_CN");
        params.put("f", "json");
        params.put("ajax", "1");

        WxResultBody<List<Map>> wxResultBody = parseWxResultBody(HttpUtils.doGet(URL_MAP.get("findListEx"), params),
                new TypeReference<WxResultBody<List<Map>>>() {}
        );
        System.out.println(wxResultBody);

        return wxResultBody;
    }

    /**
     * 获取已扫码的token
     *
     * @return
     */
    private static String getMpToken() {
        MpTokenMapper mpTokenMapper = SpringUtils.getBean(MpTokenMapper.class);
        final MpToken token = mpTokenMapper.getToken();
        return token.getToken();
    }
    /**
     * 转成java bean
     * @param jsonRes json结果字符串
     * @return
     */
    public static <T> T parseWxResultBody(String jsonRes, TypeReference<T> typeReference) {
        T wxResultBody = JsonUtils.jsonToObj(jsonRes, typeReference);
        checkIsSuccess((WxResultBody) wxResultBody);
        return wxResultBody;
    }

    public static void checkIsSuccess(WxResultBody wxResultBody) {
        // 判断是否请求成功
        if (wxResultBody == null) {
            throw new WxApiException(WxResultStatus.FAIL_NULL_RES);
        }

        if (wxResultBody.getBase_resp().getRet() == null
                || wxResultBody.getBase_resp().getRet() != 0) {
            // 需重新扫码登录
            if (wxResultBody.getBase_resp().getRet() == INVALID_SESSION.getRet()) {
                throw new RuntimeException("操作失败：" + INVALID_SESSION.getErrMsg());
            }
            // 频率控制
            if (wxResultBody.getBase_resp().getRet() == FREQ_CONTROL.getRet()) {
                throw new RuntimeException("操作失败：" + FREQ_CONTROL.getErrMsg());
            }
            throw new WxApiException(WxResultStatus.FAIL_STATUS);
        }
    }
}
